#!/user/bin/env python3
# -*- coding: utf-8 -*-
#-- anth bluedolphi ---
import os

from openpyxl import load_workbook, Workbook


def loadXls( fileName):
    print("load xls :",fileName)
    if (os.path.exists(fileName) is False):
        wb1 = Workbook()
        ws1=wb1.active
        ws1["A1"]="test"
        #wb1.create_sheet('test',0)
        wb1.save(fileName)
    return load_workbook(fileName)

def loadXlsGetSheel(fileName,sheetTitle):
    wb = loadXls(fileName)
    all_sheets = wb.get_sheet_names()
    for i in range(len(all_sheets)):
        if  wb.get_sheet_by_name(all_sheets[i])==sheetTitle:
            return wb,all_sheets[i]
    #return wb,wb.create_sheet(sheetTitle,len(all_sheets))

    return wb, wb.create_sheet(sheetTitle, 0)

def removeXlsSheet(wb,*args):
    all_sheets = wb.get_sheet_names()
    i =1
    while True:
        if i>len(all_sheets) :
            break;
        print(wb.get_sheet_by_name(all_sheets[i]).title)
        for title in args:
            if  wb.get_sheet_by_name(all_sheets[i]).title==title:
                wb.remove_sheet(wb.get_sheet_by_name(all_sheets[i]))
                all_sheets = wb.get_sheet_names()
        i+=1

def delSheetClos(sheet,cols):
    i = 0
    for col in cols :
        sheet.delete_cols(col-i)
        i+=1

def saveListToXls(saveFileName, titles, list):
    wb1, sheet = loadXlsGetSheel(saveFileName, '汇总')

    row = 1
    column = 1
    for key in titles.keys():
        sheet.cell(row=row, column=column, value=titles[key])
        column += 1

    row += 1
    for item in list:
        column = 1
        for key in titles.keys():
            sheet.cell(row=row, column=column, value=item[key])
            column += 1
        row += 1

    wb1.save(saveFileName)
    print("OK")

